# -*- coding: utf-8 -*-
import os


from pathlib import Path
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

from kj_d1.base.base import request_action


class FileUploadException(Exception):
    pass


def get_file_list(use_config, file_name=None, pagenumber=1, pagesize=10):
    if file_name is None:
        res = request_action(use_config, 'ListDoc', {
            'BotBizId': use_config.bot_biz_id,
            'PageNumber': pagenumber,
            'PageSize': pagesize
        })
    else:
        res = request_action(use_config, 'ListDoc', {
            'BotBizId': use_config.bot_biz_id,
            'PageNumber': pagenumber,
            'PageSize': pagesize,
            'Query': file_name
        })
    return res['Response']['List']


def get_temporary_key(use_config, filetype='pdf', type_key="offline", is_public=False):
    params = {
        "BotBizId": use_config.bot_biz_id,
        "FileType": filetype,
        "IsPublic": False,
        "TypeKey": type_key,
        "IsPublic": is_public

    }
    res = request_action(use_config, "DescribeStorageCredential", params)
    return res['Response']


# filePath = "./test2.txt"
def upload_file_to_cos(use_config, file_path, tmp_secret_id, tmp_secret_key, tmp_token, bucket, up_load_path):

    config = CosConfig(Region=use_config.region, SecretId=tmp_secret_id,
                       SecretKey=tmp_secret_key,
                       Token=tmp_token, Scheme='https')
    client = CosS3Client(config)
    # 使用高级接口上传一次，不重试，此时没有使用断点续传的功能
    response = client.upload_file(
        Bucket=bucket,
        Key=up_load_path,
        LocalFilePath=file_path.file_path,
        EnableMD5=False,
        progress_callback=None
    )

    rsp = response
    eTag = rsp.get('ETag')
    cosHash = rsp.get('x-cos-hash-crc64ecma')

    params = {
        "BotBizId": use_config.bot_biz_id,
        "FileName": file_path.file_all_name,
        "FileType": file_path.file_suffix,
        "CosUrl": up_load_path,
        "ETag": eTag,
        "CosHash": cosHash,
        "Size": str(os.path.getsize(file_path.file_path)),
        "AttrRange": 1
    }

    resp = request_action(use_config, "SaveDoc", params)
    return


if __name__ == '__main__':
    from kj_d1.Config.config import useConfig
    # res = get_temporary_key(useConfig)
    # res['Credentials']['Token']
    # res['UploadPath']
    # print(res)
    res = get_file_list(useConfig)
    print(res)

